package ContentManagers.Servlets;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import ContentManagers.RoleManagers.AMManager;
import ContentManagers.RoleManagers.AMSessionManager;
import ContentManagers.Models.AccountingManager;
import ContentManagers.Models.Attempt;
import ContentManagers.RoleManagers.PMManager;
import ContentManagers.RoleManagers.PMSessionManager;
import ContentManagers.Models.ProductManager;
import ContentManagers.RoleManagers.*;
import ContentManagers.Security.WebLogger;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Ervin James
 */
@WebServlet(name = "ServletPMLogin", urlPatterns = {"/ServletPMLogin"})
public class ServletManagerLogin extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            int attemptCnt = 1;
            
            resetIfTimeOut(request);
            //reset attemptCount timeouts after 5 minutes
            attemptCnt = new AttemptManager().latestAttemptCount(request.getParameter("username"), request.getRemoteAddr().toString());
            //check if attemptCount = 5
            
            if(attemptCnt < 3) //proceed to checking user credentials if attemptCount < 5
            {
                boolean checker = false;
                boolean isPasswordExpired = true;
                //System.out.println(request.getParameter("type").equals("product"));
                if(request.getParameter("type").equals("product"))
                {
                    ProductManager pm = new ProductManager();
                    pm.setUsername(request.getParameter("username"));
                    pm.setPassword(request.getParameter("password"));

                    //check if password is expired
                    isPasswordExpired=new PMManager().isPasswordExpired(pm);                 
                    if(isPasswordExpired==false)
                    {  
                        checker=new PMManager().authenticatePM(pm);
                        if(checker){
                            //delete existing sessions of this user if any exists
                            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Authentication of "+pm.getUsername()+" successful.",true);
                            boolean sessionRenew=new PMSessionManager().deleteProductSession(request.getParameter("username"));
                            request.getSession().invalidate();

                            String newSessionID;
                            HttpSession session = request.getSession();               
                            session.setAttribute("username", pm.getUsername());

                            //generate unique product manager session here
                            newSessionID = new PMSessionManager().createProductSession(request.getParameter("username"), request.getRemoteAddr());
                            session.setAttribute("sessionID", newSessionID);
                            session.setAttribute("managerType", new PMManager().getProductTypeID(pm.getUsername()));
                            
                            response.sendRedirect("./Managing Interface/managing_index.jsp");
                        }
                        else
                        {
                            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Authentication of "+pm.getUsername()+" failed.",false);
                            HttpSession session = request.getSession();
                            session.setAttribute("errorMessage","invalid");
                            //this sest, response);ction is for the LockOut mechanism. Counting from 1 to 5.
                            lockOutMechanism(attemptCnt, request, response);
                        }
                    }
                    else
                    {
                        WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Authentication of "+pm.getUsername()+" failed. Password is expired.",false);
                        HttpSession session = request.getSession();
                        session.setAttribute("errorMessage","invalid");
                        //this section is for the LockOut mechanism. Counting from 1 to 5.
                        lockOutMechanism(attemptCnt, request, response);
                    }
                }
                else if (request.getParameter("type").equals("accounting"))
                {
                    AccountingManager am = new AccountingManager();
                    am.setUsername(request.getParameter("username"));
                    am.setPassword(request.getParameter("password"));

                    //check if password is expired
                    isPasswordExpired=new AMManager().isPasswordExpired(am);                 
                    if(isPasswordExpired==false)
                    {   
                        //check for authentication
                        checker=new AMManager().authenticateAM(am);
                        if(checker){
                            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Authentication of "+am.getUsername()+" successful.",true);
                            //delete existing sessions of this user if any exists
                            boolean sessionRenew=new AMSessionManager().deleteAccountingSession(request.getParameter("username"));
                            request.getSession().invalidate();

                            String newSessionID;
                            HttpSession session = request.getSession();
                            session.setAttribute("username", am.getUsername());

                            //generate unique accounting manager session here
                            newSessionID = new AMSessionManager().createAccountingSession(request.getParameter("username"), request.getRemoteAddr());
                            session.setAttribute("sessionID", newSessionID);

                                response.sendRedirect("./Managing Interface/managing_index.jsp");
                        }
                        else
                        {
                            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Authentication of "+am.getUsername()+" failed.",false);
                            HttpSession session = request.getSession();
                            session.setAttribute("errorMessage","invalid");
                            //this section is for the LockOut mechanism. Counting from 1 to 5.
                            lockOutMechanism(attemptCnt, request, response);
                        }
                    }
                    else
                    {
                        WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Authentication of "+am.getUsername()+" failed. Password is expired.",false);
                        HttpSession session = request.getSession();
                        session.setAttribute("errorMessage","invalid");
                        //this section is for the LockOut mechanism. Counting from 1 to 5.
                        lockOutMechanism(attemptCnt, request, response);
                    }
                }
                else
                {
                    response.sendRedirect("./Managing Interface/manager_login.jsp");
                }
                
                }
                else
                lockOutMechanism(attemptCnt, request, response);
            
        } finally {            
            out.close();
        }
        
        
    }

    public static void resetIfTimeOut(HttpServletRequest request)
   {
       boolean clear = new AttemptManager().checkTimeStamp();
       if(true == clear)
       {
           HttpSession session = request.getSession();
           session.setAttribute("formLockout", "off");                       
       }
       
   }
   
   public void lockOutMechanism(int attemptCnt, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
   {    
       
       boolean checker, logAttempt = false;
       
        checker = new AttemptManager().checkIfAlreadyExists(request.getParameter("username"));

                        if(checker == false)   
                        {   Attempt newAttempt = new Attempt();
                            newAttempt.setUsername(request.getParameter("username"));
                            newAttempt.setAttemptCount(attemptCnt);
                            newAttempt.setFromIP(request.getRemoteAddr());
                            logAttempt = new AttemptManager().addAttemptRecord(newAttempt);
                            //System.out.print("umabot ako dito");
                        }
                        else
                        {   
                            if(attemptCnt < 3)
                            {
                                java.util.Date date= new java.util.Date();
                                checker = new AttemptManager().addAttemptCount(request.getParameter("username"), attemptCnt++, (new Timestamp(date.getTime())).toString(), request.getRemoteAddr().toString());
                                //System.out.print("dito rin");
                            }
                            else if(attemptCnt == 3)
                            {
                                WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Log in lockout triggered.",false); 
                                HttpSession session = request.getSession();
                                session.setAttribute("formLockout", "on");
                                //System.out.print(session.getAttribute("formLockout") + "dito rin rin");
                            }
                            
                        }
                        
                        response.sendRedirect("./Managing Interface/manager_login.jsp");
   }
   
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
